import { accountLogin, mobileLogin } from '@/api/user';
import { TOKEN, USERINFO, PERMISSION, MENUALL, FIRSTPATH } from '@/common/constant/sessionKey';
import { clear, getItem, removeItem, setItem, setToken } from '@/utils/auth';
import { asyncRoutes } from '@/router';

const state = {
    userinfo: getItem(USERINFO, {}),
    token: getItem(TOKEN, ''),
    roles: [],
    permission: getItem(PERMISSION, {}),
    menuAll: getItem(MENUALL, []),
    firstLogin: getItem('FIRSTLOGIN', false),
    firstPath: getItem(FIRSTPATH, []),
    isFullScreen: false
};

const mutations = {
    SET_TOKEN(state, token) {
        state.token = token;
        setItem(TOKEN, token);
    },
    SET_USERINFO(state, userInfo) {
        state.userInfo = userInfo;
        setItem(USERINFO, userInfo);
    },
    SET_ROLES(state, roles) {
        state.roles = roles;
    },
    SET_PERMISSION: (state, permission) => {
        let result = [];

        function getCode(list) {
            list.forEach(ele => {
                if (ele.button) {
                    const code = ele.code;
                    result.push(code);
                }
            });
        }
        getCode(permission);
        state.permission = {};
        result.forEach(ele => {
            state.permission[ele] = true;
        });
        setItem(PERMISSION, state.permission);
    },
    SET_MENU_ALL: (state, menuAll) => {
        let newMenu = [];
        let menuCode = {};
        menuAll.forEach(ele => {
            if (!ele.button) {
                const code = ele.code;
                menuCode[code] = true;
            }
        });
        for (let item1 of asyncRoutes) {
            let flag = false;
            let item = {};
            if (menuCode[item1.meta.code]) {
                flag = true;
                item = item1;
                let children = [];
                for (let item2 of item1.children) {
                    if (menuCode[item2.meta.code]) {
                        children.push(item2);
                    }
                }
                item.children = children;
                item.redirect = children[0].path;
            }
            if (flag) {
                newMenu.push(item);
            }
        }
        if (newMenu.length != 0) {
            state.firstPath = newMenu[0].path;
            setItem(FIRSTPATH, state.firstPath);
        } else {
            state.firstPath = '';
            setItem(FIRSTPATH, state.firstPath);
        }

        state.menuAll = [];
        setItem(MENUALL, state.menuAll);
    },
    SET_FIRST_LOGIN(state, firstLogin) {
        state.firstLogin = firstLogin;
        setItem('FIRSTLOGIN', state.firstLogin);
    },
    SET_FULLSCREEN(state) {
        state.isFullScreen = !state.isFullScreen;
    }
};

const actions = {
    login({ commit }, userInfo) {
        return new Promise((resolve, reject) => {
            if (userInfo.loginname) {
                accountLogin(userInfo).then(res => {
                    const { token, userId, userName, yardName, deptName, userTel, userMenus, firstLogin, personType, yardId } = res;
                    commit('SET_TOKEN', token);
                    commit('SET_PERMISSION', userMenus);
                    commit('SET_MENU_ALL', userMenus);
                    commit('SET_FIRST_LOGIN', firstLogin);
                    setToken('session_id', userId);
                    setToken('auth_key', token);
                    setToken('userName', userName);
                    setToken('yardName', yardName);
                    setToken('deptName', deptName);
                    setToken('userTel', userTel);
                    setToken('firstLogin', firstLogin);
                    setToken('personType', personType);
                    setToken('yardId', yardId);
                    sessionStorage.setItem('tabViews', '');
                    resolve();
                }).catch(err => {
                    reject(err);
                });
            } else {
                mobileLogin(userInfo).then(res => {
                    const { token, userId, userName, yardName, deptName, userTel, userMenus, firstLogin, personType, yardId } = res;
                    commit('SET_TOKEN', token);
                    commit('SET_PERMISSION', userMenus);
                    commit('SET_MENU_ALL', userMenus);
                    commit('SET_FIRST_LOGIN', firstLogin);
                    setToken('session_id', userId);
                    setToken('auth_key', token);
                    setToken('userName', userName);
                    setToken('yardName', yardName);
                    setToken('deptName', deptName);
                    setToken('userTel', userTel);
                    setToken('firstLogin', firstLogin);
                    setToken('personType', personType);
                    setToken('yardId', yardId);
                    sessionStorage.setItem('tabViews', '');
                    resolve();
                }).catch(err => {
                    reject(err);
                });
            }
        });
    },

    getInfo({ commit }) {
        return new Promise(resolve => {
            commit('SET_ROLES', ['*']);
            resolve(['*']);
        });
    },

    logout({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '');
            commit('SET_USERINFO', {});
            commit('SET_PERMISSION', []);
            commit('SET_MENU_ALL', []);
            commit('SET_FIRST_LOGIN', false);
            clear();
            resolve('操作成功');
        });
    },

    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '');
            commit('SET_ROLES', []);
            removeItem(TOKEN);
            resolve();
        });
    },

    setFullScreen({ commit }) {
        return new Promise(resolve => {
            commit('SET_FULLSCREEN');
            resolve();
        });
    }
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
};
